package com.zhaorujie.rpc.core.route.impl;

import com.zhaorujie.rpc.core.route.RpcLoadBalance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 赵汝杰
 * @version v1.0
 * @description RpcLoadBalanceRoundStrategy
 * @date 2024/3/11
 **/
public class RpcLoadBalanceRoundStrategy implements RpcLoadBalance {

    private static final Logger logger = LoggerFactory.getLogger(RpcLoadBalanceRoundStrategy.class);
    private final ConcurrentHashMap<String, AtomicInteger> routeCountEachJob = new ConcurrentHashMap<>();

    @Override
    public String route(String serviceKey, List<String> addressList) {

        AtomicInteger atomicInteger = routeCountEachJob.get(serviceKey);

        if (atomicInteger == null || atomicInteger.get() > 10000) {
            atomicInteger = new AtomicInteger(0);
        } else {
            atomicInteger.addAndGet(1);
        }
        routeCountEachJob.put(serviceKey, atomicInteger);
        return addressList.get(atomicInteger.get() % addressList.size());
    }
}
